package com.zh.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhanghuan
 * @date: 2022/10/9 20:31
 * @description: create it
 * <p>
 * 可重入锁：同一个线程在外层方法获取锁的时候，再进入该线程内层方法会自动获取锁（前提：锁的是同一个对象），不会因为之前已经获取锁没释放而阻塞
 * ReentrantLock和synchronized都是可重入锁
 * 可重入锁原理：每个锁对象拥有一个锁计数器和一个指向持有该锁的线程的指针
 */
public class ReEntryLockDemo {

    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "\t" + "---m1 come in");
        m2();
        System.out.println(Thread.currentThread().getName() + "\t" + "---m1 end");
    }

    public synchronized void m2() {
        System.out.println(Thread.currentThread().getName() + "\t" + "---m2 come in");
        m3();
        System.out.println(Thread.currentThread().getName() + "\t" + "---m2 end");
    }

    public synchronized void m3() {
        System.out.println(Thread.currentThread().getName() + "\t" + "---m3 come in");
    }

    static Lock lock = new ReentrantLock();


    public static void main(String[] args) {
//        new ReEntryLockDemo().m1();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "---外层 come in ");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "---内层 come in");
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }

        }, "a").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "---外层 come in ");
            } finally {
                lock.unlock();
            }
        }, "b").start();


    }

    private static void reEntryM1() {
        final Object object = new Object();
        new Thread(() -> {
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + "\t" + "---外层调用");
                synchronized (object) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "---中层调用");
                    synchronized (object) {
                        System.out.println(Thread.currentThread().getName() + "\t" + "---内层调用");
                    }
                }
            }
        }, "t1").start();
    }
}
